<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="table-view">
      <template #form="{ form }">
        <XForm style="box-shadow: 0px 1px 0px 0px #eff3fe" class="mb-[9px] pt-[10px]" ref="form" :fieldList="fieldList" :options="formOption" :formData="form">
          <template #ShopCascade>
            <SelectsShopCascade :isHandle="true" v-model:platform="form.platform_id" v-model:site="form.site_id" v-model:shop="form.shop_id" multiple class="h-[32px]" />
          </template>
          <template #ShipWarehouse>
            <SelectWarehouse placeholder="发货仓库" :isHandle="true" multiple collapseTags v-model:modelValue="form.shipping_warehouse_id" style="width: 240px" />
          </template>

          <template #RecipientCountry>
            <SelectCountry placeholder="收货国家" :isHandle="true" multiple collapseTags v-model:modelValue="form.recipient_country" style="width: 200px" labelKey2="true" valueKey="country" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <div class="w-[100%]">
          <div class="w-[100%] flex">
            <el-dropdown>
              <el-button type="primary" class="btn">
                导 出
                <div class="dk-iconfont icon-ArrowDown ml-[4px]"></div>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="importHandleClick(1)" :disabled="!isPermission([reportAuthList.sales_trend.exportSkuDetail])">导出SKU明细数据</el-dropdown-item>
                  <el-dropdown-item @click="importHandleClick(2)" :disabled="!isPermission([reportAuthList.sales_trend.exportOrderDetail])">导出订单明细数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="danger" class="ml-[16px]" @click="aaaaa"> 异常账单 </el-button>

            <div class="ml-auto">
              <el-checkbox v-model="tag" true-value="v2" false-value="v1" v-if="isPermission([reportAuthList.sales_trend.v2])">财务接口V2</el-checkbox>
            </div>
          </div>

          <div id="echart-view" v-loading="echartLoading"></div>

          <div class="profit-etail">
            <p class="item flex items-center" v-for="item in profitColumn" :key="item.key">
              <span class="label flex items-center">
                {{ item.label }} {{ item.type == "currency" ? `(${currency})` : "" }}
                <el-tooltip class="box-item" effect="dark" placement="top">
                  <template #content>
                    <div class="max-w-[260px]" v-html="item.tooltips"></div>
                  </template>
                  <div class="dk-iconfont icon-Warning"></div>
                </el-tooltip>
              </span>
              <span class="value ml-[4px]">{{ profitData.detail[item.key] }} {{ item.type ? "" : "%" }}</span>
            </p>
          </div>
        </div>
      </template>

      <template #HeaderContent="{ column }">
        {{ column.title }}
        <el-tooltip class="box-item" effect="dark" placement="top" raw-content>
          <template #content>
            <div class="max-w-[200px]">{{ tooltips[column.field] }}</div>
          </template>
          <div class="dk-iconfont icon-Warning"></div>
        </el-tooltip>
      </template>
    </VTable>
    <DerivedCenter ref="DerivedCenterRef" @callback="callback"></DerivedCenter>
  </VPage>
</template>

<script setup lang="jsx">
import XForm from "@/components/XForm/index.vue"
import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"

import SelectWarehouse from "@/components/Selects/SelectWarehouse/index.vue"

import SelectCountry from "@/components/Selects/SelectCountry/index.vue"
import DerivedCenter from "@/components/DerivedCenter"

import { profitSalesTrend, profitComposite, profitOverflow, shopExpenses, profitSku, profitDetail } from "./api"
import * as echarts from "echarts"
import { formatDate } from "@/utils"
import { ElMessage } from "element-plus"
import { isPermission } from "@/hooks/permission.js"
import { reportAuthList } from "@/Auth/report.js"
import { reactive } from "vue"

const router = useRouter()
const aaaaa = () => {
  //
  router.push(`/report/sales-trend/groupArchive`)
}
// 导出中心
const DerivedCenterRef = ref()
const importType = ref("")
const importHandleClick = async (e) => {
  let condition = tableRef.value.getQueryForm()
  condition = initForm(condition)

  let parmas = {
    tag_name: e == 1 ? "expense_report_shop_dimension_sku" : "expense_report_order_dimension_sku",
    exportName: e == 1 ? "【订单利润报表】SKU明细导出" : "【订单利润报表】订单明细导出",
    condition,
  }

  // if (e == 1) {
  //   parmas.defaul_tag_name = "expense_report_shop"
  //   parmas.defaul_import_name = "【订单利润报表】店铺费用导出"
  // }
  importType.value = e
  DerivedCenterRef.value.open(parmas)
}

const tag = ref("v1")
const callback = () => {
  if (importType.value == 1) {
    DerivedCenterRef.value.outerExport("expense_report_shop", "【订单利润报表】店铺费用导出", "all")
  }
}
const tableRef = ref()

const tooltips = {
  // 销售收入
  sales_revenue: '根据查询条件统计汇总"付款"类型单据的产品销售收入，除OTTO/Kaufland/Shein入驻欧洲站外，其他平台都是不含税金额',
  // 运费收入
  freight_revenue: '根据查询条件统计汇总"付款"类型单据的运费收入，除OTTO/Kaufland/Shein入驻欧洲站外，其他平台都是不含税金额',
  // 退款金额
  refund_revenue: "根据查询条件统计汇总”退款“类型单据的“收入”，汇总了“税费收入”和“扣除客户税费”，属于不含税退款金额",
  // 优惠金额
  discount_amount: '根据查询条件统计汇总"付款"类型单据的优惠金额，除OTTO/Kaufland/Shein入驻欧洲站外，其他平台都是不含税金额',
  // 其他收入
  other_revenue: '根据查询条件统计汇总"付款"类型单据的其他收入，除OTTO/Kaufland/Shein入驻欧洲站外，其他平台都是不含税金额',
  // 税费收入
  tax_revenue: '根据查询条件统计汇总"付款"类型单据的税费收入，除OTTO/Kaufland/Shein入驻欧洲站外，汇总其他费用的“税费”',
  // 扣除客户税费
  deduct_customer_tax: '根据查询条件统计汇总"付款"类型单据的扣除客户支付税费，正常情况为等于“税费收入 * -1”，目前亚马逊日本站点没有通过平台代缴税费，所以亚马逊日本站订单不存在“扣除客户支付税费”',

  // 平台佣金
  trade_commission: '根据查询条件统计汇总"付款/退款"类型单据的平台佣金',
  // FBA操作费
  fba_operate_fee: "目前只有亚马逊订单和通过亚马逊多渠道发货的订单存在FBA操作费，包含亚马逊FBA订单的出库操作费用和尾程派送费用",
  // 平台其他支出
  other_platform_expenses: "统计各平台返回的未归属到公司费用项的订单费用，例如：亚马逊日本站的“亚马逊积分”、“出口报关费”、“数字服务费”、“开票订单更快获得付款的费用”等等",

  // 平台仓储费
  shop_platform_warehouse: "根据查询条件统计汇总平台仓储费，目前只有亚马逊平台存在“平台仓储费”，来源于店铺后台仓储费报告数据",
  // 长期仓储费
  shop_platform_warehouse_long: "根据查询条件统计汇总长期仓储费，目前只有亚马逊平台存在“长期仓储费”，来源于店铺后台长期仓储费报告数据",
  // 库存仓储超量费
  shop_platform_warehouse_beyond: "根据查询条件统计汇总库存仓储超量费，目前只有亚马逊平台存在“库存仓储超量费”，来源于店铺后台库存仓储超量费报告数据",
  // 广告费
  shop_advertise_fee:
    '根据查询条件统计汇总“付款/退款/其他”类型单据的广告费，其中ebay订单存在订单维度（付款/退款）的广告费，其他平台的广告费都是店铺维度（"其他"类型单据），亚马逊平台广告分为“SP/SB/SD”三种，来源于亚马逊广告平台的实时报告，属于发生制的广告费',
  // 亚马逊入库配置费
  shop_amazon_in_storage: "根据查询条件统计汇总亚马逊入库配置费，目前只有亚马逊平台存在“亚马逊入库配置费”",

  // 采购成本
  purchase_cost: "订单商品的采购成本，平台仓/海外仓发货的订单，订单的采购成本从【头程】-【运费池】获取，国内仓发货订单的采购成本取对应仓库的加权平均价格",
  // 头程运费
  head_trip_freight: "平台仓/海外仓发货商品的头程运费，由【头程】-【运费池】返回",
  // 关税
  tariff: "平台仓/海外仓发货商品的关税，由头程运费池返回，物流同事合并到头程费用中导入到了运费池",
  // 海外仓操作费
  overseas_warehouse_operate_fee: "其他非亚马逊的平台仓发货费用，目前只有Walmart的平台仓发货订单存在该费用",
  // 尾程运费
  warehouse_freight: "海外仓发货和国内直发订单的尾程运费",
  // 包装成本
  package_cost: "商品系统SKU资料中，对应订单SKU绑定的辅料成本",
  // 自定义费用（仓库管理成本）
  custom_expense_items: "系统预设的海外仓预估仓储费/入库操作费/出库操作费，在【自定义费用项设置】中维护",
  // 自定义费用（其他费用成本）
  custom_expense_items_other: "系统预设的其他费用成本，在【自定义费用项设置】中维护",
  // 自定义导入费用
  custom_import_items: "由人工在【自定义费用导入】中导入的订单费用",
  // 预设运营费用
  operate_cost: "在系统【订单来源渠道管理】中设置的各店铺的预设运营费用",
  // 汇率折损
  exchange_rate_impairment: "在系统【订单来源渠道管理】中设置的各店铺的汇率折损",
  // 店铺费用
  shop_fee:
    "各类未归属到系统订单的费用，例如亚马逊的优惠券费用、VINE费用、清仓/移仓费用、店租等等，由于广告费/仓储费/入库配置费单独显示，所以列表上显示的店铺费用中不包含这部分金额，但实际这些费用属于“店铺费用”",
}

const getTime = () => {
  const temp = new Date()
  temp.setTime(temp.getTime() - 3600 * 1000 * 24 * 30)
  return [formatDate(new Date(temp.setHours(0, 0, 0, 0))), formatDate(new Date(new Date().setHours(23, 59, 59, 0)))]
}
// 收入总和
const countRevenue = ref(0)
// 列表配置
const tableOptins = reactive({
  formConfig: {
    save: "/oms/report/sales-trend", // 必填，唯一
    data: {
      snRange: { type: "order_sn", value: "" },
      timeRange: { type: "shipping_time", value: getTime() },
      platform_id: [],
      site_id: [],
      shop_id: [],
      shipping_warehouse_id: [],
      recipient_country: [],
      granularity: "day",
      currency: "USD",

      stage: 1,
    },
  },
  border: "full",
  showOverflow: true,
  columns: [
    {
      title: "收入",
      align: "center",
      slots: {
        header: ({ row }) => {
          return (
            <div class="pl-[16px]">
              收入 （{countRevenue.value}）
              <el-tooltip class="box-item" content="计算公式：收入=销售收入+运费收入+退款金额+优惠金额+其他收入+税费收入 +扣除客户税费" effect="dark" placement="top">
                <div class="dk-iconfont icon-Warning"></div>
              </el-tooltip>
            </div>
          )
        },
      },

      children: [
        { title: "销售收入", field: "sales_revenue", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "运费收入", field: "freight_revenue", minWidth: 100, slots: { header: "HeaderContent" } },
        { title: "退款金额", field: "refund_revenue", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "优惠金额", field: "discount_amount", minWidth: 110, slots: { header: "HeaderContent" } },
        { title: "其他收入", field: "other_revenue", minWidth: 100, slots: { header: "HeaderContent" } },
        { title: "税费收入", field: "tax_revenue", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "扣除客户税费", field: "deduct_customer_tax", minWidth: 140, slots: { header: "HeaderContent" } },
      ],
    },

    {
      title: "支出",
      align: "center",
      children: [
        { title: "平台佣金", field: "trade_commission", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "FBA操作费", field: "fba_operate_fee", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "平台其他支出", field: "other_platform_expenses", minWidth: 130, slots: { header: "HeaderContent" } },
        { title: "平台仓储费", field: "shop_platform_warehouse", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "长期仓储费", field: "shop_platform_warehouse_long", minWidth: 130, slots: { header: "HeaderContent" } },
        { title: "库存仓储超量费", field: "shop_platform_warehouse_beyond", minWidth: 150, slots: { header: "HeaderContent" } },

        { title: "广告费", field: "shop_advertise_fee", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "亚马逊入库配置费", field: "shop_amazon_in_storage", minWidth: 160, slots: { header: "HeaderContent" } },

        { title: "采购成本", field: "purchase_cost", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "头程运费", field: "head_trip_freight", minWidth: 120, slots: { header: "HeaderContent" } },
        { title: "关税", field: "tariff", minWidth: 100, slots: { header: "HeaderContent" } },

        { title: "海外仓入库费", field: "overseas_warehousing_fee", minWidth: 120 },
        { title: "海外仓操作费", field: "overseas_warehouse_operate_fee", minWidth: 130, slots: { header: "HeaderContent" } },
        { title: "尾程运费", field: "warehouse_freight", minWidth: 100, slots: { header: "HeaderContent" } },
        { title: "包装成本", field: "package_cost", minWidth: 100, slots: { header: "HeaderContent" } },
        { title: "自定义费用（仓库管理成本）", field: "custom_expense_items", minWidth: 240, slots: { header: "HeaderContent" } },
        { title: "自定义费用（其他费用成本）", field: "custom_expense_items_other", minWidth: 240, slots: { header: "HeaderContent" } },
        { title: "自定义导入费用", field: "custom_import_items", minWidth: 150, slots: { header: "HeaderContent" } },
        { title: "预设运营费用", field: "operate_cost", minWidth: 130, slots: { header: "HeaderContent" } },
        { title: "汇率折损", field: "exchange_rate_impairment", minWidth: 100, slots: { header: "HeaderContent" } },
        { title: "店铺费用", field: "shop_fee", minWidth: 120, slots: { header: "HeaderContent" } },
      ],
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        // if (form?.sales_id?.length) {
        //   form.sales_id = form.sales_id.map((v) => v?.[v.length - 1])
        // }
        // form.tag = tag.value
        form = initForm(form)
        handleSearch(form)
        return getTableData(form)
      },
    },
  },
})
const initForm = (form) => {
  if (form.order_sn) {
    form.order_sn = form.order_sn.split("\n")?.filter((v) => !!v.trim())
    form.order_sn = form.order_sn?.map((v) => v.trim())
  }
  if (form.platform_order_sn) {
    form.platform_order_sn = form.platform_order_sn.split("\n")?.filter((v) => !!v.trim())
    form.platform_order_sn = form.platform_order_sn?.map((v) => v.trim())
  }
  form.tag = tag.value
  return form
}
const profitColumn = ref([
  { label: "总订单数（单）", key: "orderQuantity", type: "num", tooltips: "根据查询条件筛选统计系统订单数量，不过滤任何订单状态单据（不统计退款单），以系统订单号去重" },
  {
    label: "总销售额",
    key: "amount",
    type: "currency",
    tooltips: "统计“总订单数”对应的总销售额（不含税，不含退款金额）<br/  >计算公式：总销售额=销售收入+运费收入+优惠金额+其他收入+税费收入 +扣除客户税费",
  },
  { label: "总销售毛利润", key: "totalSalesProfit", type: "currency", tooltips: "根据查询汇总收入和支出金额，再减去运营成本得出总销售毛利润。<br/>计算公式：总销售毛利润=收入+支出-运营成本" },
  { label: "销售毛利率", key: "saleGrossSalesRate", tooltips: "计算公式：销售毛利率=总销售毛利润 / 收入" },
  { label: "退款率", key: "refundRate", tooltips: "计算公式：退款率=退款金额/总销售额 （总退款金额：统计交易类型为“退款”的“收入”汇总）" },
  { label: "广告费率", key: "advRate", tooltips: "广告费率 = 总广告费 / 总销售额 （总广告费：包含订单维度和店铺维度的广告费）" },
  { label: "平台佣金率", key: "commissionRate", tooltips: "平台佣金率=总平台佣金/总销售额（总平台佣金：包含订单“付款/退款”类型的平台佣金）" },
])

const currency = ref("")

const formOption = ref({ inline: true })

const publicStyle = { style: { width: "240px" } }
const fieldList = ref([
  {
    field: "shopCascade",
    slot: "ShopCascade",
  },
  {
    field: "timeRange",
    clearable: false,
    type: "dateTimeRangeNorm",
    select: [
      { label: "发货时间", value: "shipping_time" },
      { label: "下单时间", value: "order_time" },
      { label: "付款时间", value: "pay_time" },
      { label: "添加时间", value: "order_system_time" },
      { label: "结算时间", value: "settlement_time" },
    ],
    selectStyle: { width: "120px" },
  },
  // ----------------------------------------
  {
    field: "order_status",
    type: "select",
    isHandle: true,
    style: { width: "200px" },
    multiple: true,
    collapseTags: true,
    origin: "order_status",
    options: {
      placeholder: "订单状态",
      data: [],
    },
  },
  {
    field: "sales_id",
    type: "cascader",
    itemProps: { placeholder: "销售人员" },
    style: { width: "200px" },
  },
  {
    field: "shipping_warehouse_id",
    slot: "ShipWarehouse",
    type: "select",
    multiple: true,
    collapseTags: true,
  },
  {
    field: "snRange",
    placeholder: "可批量搜索",
    type: "textarea",
    ...publicStyle,
    selectStyle: { width: "120px" },
    select: [
      { label: "系统订单号", value: "order_sn" },
      { label: "平台订单号", value: "platform_order_sn" },
    ],
  },

  {
    field: "currency",
    type: "select",
    clearable: false,
    options: {
      placeholder: "币种",
      data: [
        { label: "RMB", value: "RMB" },
        { label: "USD", value: "USD" },
      ],
    },
    style: { width: "160px" },
  },
  {
    field: "granularity",
    type: "select",
    clearable: false,
    options: {
      placeholder: "数据周期",
      data: [
        { label: "天", value: "day" },
        { label: "周", value: "week" },
        { label: "月", value: "month" },
      ],
    },
    style: { width: "140px" },
  },
  {
    field: "recipient_country",
    slot: "RecipientCountry",
  },
  {
    field: "shipping_status",
    type: "select",
    options: {
      placeholder: "发货状态",
      data: [
        { label: "未发货", value: 0 },
        { label: "已发货", value: 1 },
      ],
    },
    style: { width: "140px" },
  },
  {
    field: "stage",
    type: "select",
    clearable: false,
    options: {
      placeholder: "费用类型",
      data: [
        { label: "预估", value: 1 },
        { label: "结算", value: 2 },
      ],
    },
    style: { width: "140px" },
  },
])
const echartHeight = ref("0")
onMounted(async () => {
  setTimeout(() => {
    let h1 = document.getElementsByClassName("vx-table__content")[0]?.clientHeight
    let h2 = h1 - (document.getElementsByClassName("profit-etail")[0]?.clientHeight + 240)
    echartHeight.value = h2 + "px"
  }, 100)
})

const loading = ref(false)
const echartLoading = ref(false)
const tableLoading = ref(false)
const handleSearch = async (param) => {
  try {
    let params = { ...param }
    delete params.snRange
    currency.value = params.currency
    initEcharts(params)
    getComposite(params)
    loading.value = false
  } catch (e) {
    loading.value = false
    throw Error(e)
  }
}
const profitData = ref({
  detail: {},
  tableData: [],
})
const getComposite = async (params) => {
  let res = await profitComposite(params)
  profitData.value.detail = res.data
}

const getTableData = async (params) => {
  tableLoading.value = true
  try {
    let res = await profitOverflow(params)
    res.data.warehouse_freight = (Number(res.data.local_warehouse_freight) + Number(res.data.overseas_warehouse_freight)).toFixed(2)
    res.data.shop_advertise_fee = (Number(res.data.advertise_fee) + Number(res.data.shop_advertise_fee)).toFixed(2)
    tableLoading.value = false

    let countValue = tableOptins.columns[0].children.map((v) => res.data[v.field])
    countRevenue.value = eval(countValue.join("+")).toFixed(2)
    return { data: [{ ...res.data }], total: 0 }
  } catch (error) {
    tableLoading.value = false
  }
}
const initEcharts = async (params) => {
  echartLoading.value = true
  const root = document.documentElement
  let color = getComputedStyle(root).getPropertyValue("--base-text-color").trim()
  try {
    let res = await profitSalesTrend(params)
    var chartDom = document.getElementById("echart-view")
    var myChart = echarts.init(chartDom)
    var option
    option = {
      tooltip: {
        trigger: "axis",
        backgroundColor: "var(--base-color)",
        formatter: (row) => {
          let ahtml = ""
          row.forEach((item) => {
            ahtml += `<div style='color:var(--base-text-color);'>${item.marker} ${item.seriesName}: ${item.value} ${item.seriesName == "订单量" ? "单" : currency.value}</div>`
          })
          return `<div>
            <div>${row[0].name}</div>
            ${ahtml}
          </div>`
        },
      },
      legend: {
        data: ["订单量", "销售额"],
        textStyle: {
          color: color,
        },
      },
      grid: { left: "3%", right: "3%", bottom: "3%", containLabel: true },
      xAxis: {
        type: "category",

        boundaryGap: false,
        data: res.data.date,
      },
      yAxis: [
        {
          type: "value",
          name: "订单量",
          axisTick: { show: false },
          splitNumber: 5,
        },
        {
          type: "value",
          name: "销售额",
          axisTick: { show: false },
          axisLine: { show: false },
          splitLine: { show: false },
          splitNumber: 5,
        },
      ],

      series: [
        { name: "订单量", type: "line", showSymbol: false, smooth: true, stack: "Total", data: res.data.quantity },
        { name: "销售额", type: "line", yAxisIndex: 1, showSymbol: false, smooth: true, stack: "Total", data: res.data.amount },
      ],
    }
    option && myChart.setOption(option)
    echartLoading.value = false
  } catch (err) {
    console.warn(err)
    echartLoading.value = false
  }
}
const bgpink = ref("pink")
defineExpose({})
</script>

<style lang="scss" scoped>
.report-body {
  padding: 0 8px;
  overflow: auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  :deep(.el-form) {
    padding-bottom: 8px;
    flex-wrap: wrap;
    gap: 10px;
    .el-form-item {
      margin: 0 !important;
    }
  }
}
.body {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.profit-etail {
  display: flex;
  line-height: 30px;
  .item {
    flex: 1;
    .label {
    }
    .value {
    }
  }
}
:deep(.el-dropdown) {
  .el-button {
    height: 28px;
  }
}
:deep(.table-view) {
  .vxe-table--body-wrapper {
    height: 58px !important;
  }
  .vxe-pager {
    display: none;
  }
  #echart-view {
    width: 100%;
    height: v-bind(echartHeight);
    flex: 1;
  }
}
</style>
